package com.water.wl.newwater;

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.water.wl.newwater.adapter.TestAdapter;
import com.water.wl.newwater.api.ApiClient;
import com.water.wl.newwater.bean.ListEntity;
import com.water.wl.newwater.bean.Tweet;
import com.water.wl.newwater.bean.TweetsList;
import com.water.wl.newwater.bean.WaterTest;
import com.water.wl.newwater.util.XmlUtils;

import org.json.JSONArray;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

/**
 * Created by wds1993225 on 2016/3/10.
 */
public class ExploreTab extends Fragment {

    private SwipeRefreshLayout swipeRefreshLayout;
    private ListView listView;
    private View view;
    private TestAdapter testAdapter;
    //private List<WaterTest> list = new ArrayList<WaterTest>();
    private String partUrl = "action/api/tweet_list";
    //private String [] data= {"monkey.d.Luffy","double kill","like you","sb"};
    private List<Tweet> arrayList = new ArrayList<Tweet>();
    private ParserTask mParserTask;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.explorer_list,null);
        //initData();
        initHttpData();
        //initView();

        return view;
    }
    private void initView(){
        swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipeRefresh);
        listView = (ListView)view.findViewById(R.id.listView);
        testAdapter = new TestAdapter(getActivity()
                ,R.layout.tweet_list_item,arrayList);
        Log.i("AAA",String.valueOf(arrayList));
        listView.setAdapter(testAdapter);

    }

   /* private void initData(){
        for(int i = 0;i<data.length;i++){
            WaterTest waterTest = new WaterTest(data[i]);
            list.add(waterTest);
        }
    }*/
    private void initHttpData(){
        RequestParams params = new RequestParams();
        params.put("uid",1);
        params.put("pageIndex",0);
        params.put("pageSize",20);
        String url = partUrl;
        ApiClient.get(url, params, responseHandler);
    }
    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            executeParserTask(responseBody);

           /* Message message = new Message();
            message.what = 0;
            handler.sendMessage(message);*/
            Log.i("响应成功", String.valueOf(responseBody));

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            Log.i("网络问题",error.getMessage());
        }
    };
    class ParserTask extends AsyncTask<Void, Void, String> {

        private final byte[] reponseData;
        private List<Tweet> list;

        public ParserTask(byte[] data) {
            this.reponseData = data;
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                ListEntity<Tweet> data = parseList(new ByteArrayInputStream(
                        reponseData));
                list = data.getList();
                Log.i("解析成功",String.valueOf(list));

            } catch (Exception e) {
                e.printStackTrace();

            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            //Log.i("等等",String.valueOf(arrayList));

            executeOnLoadDataSuccess(list);
            //executeOnLoadFinish();
        }
    }
    private TweetsList parseList(InputStream is) throws Exception {
        TweetsList list = XmlUtils.toBean(TweetsList.class, is);
        Log.i("数据解析为",String.valueOf(list));
        //ArrayList<Tweet> = XmlUtils.toBean(ArrayList<Tweet>.class,is);
        return list;
    }

    private void executeOnLoadDataSuccess(List<Tweet> data) {
        /*testAdapter = new TestAdapter(getActivity()
                ,android.R.layout.simple_list_item_1,data);*/
        //arrayList = data;
        arrayList.addAll(data);
        Log.i("数据为",String.valueOf(arrayList));
        initView();


        //tweetAdapter.addData(data);

    }
    private void executeParserTask(byte[] data) {
        mParserTask = new ParserTask(data);
        mParserTask.execute();
    }

    /*//利用重写getParams方法传入POST参数
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,partUrl,new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

        }
    },new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> map = new HashMap<>();
            map.put("a","a");
            map.put("s","s");
            return map;

        }
    };*/

}
